﻿// Copyright (c) ZhangPeihang. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Extensions.Logging;
using System.Text;

namespace LaserMark.Logging
{
    public class FileLogger : ILogger
    {
        public IDisposable? BeginScope<TState>(TState state) where TState : notnull => default!;

        public bool IsEnabled(LogLevel logLevel) => true;

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
        {
            if (!Directory.Exists(AppContext.BaseDirectory + "Log"))
            {
                Directory.CreateDirectory(AppContext.BaseDirectory + "Log");
            }

            switch (logLevel)
            {
                case LogLevel.Information:
                    Write($"{AppContext.BaseDirectory}Log\\Log_{DateTime.Today.ToString("yyyy-MM-dd")}.txt", "Info", state);
                    break;

                case LogLevel.Error:
                    if (!Directory.Exists(AppContext.BaseDirectory + "Log\\Error"))
                    {
                        Directory.CreateDirectory(AppContext.BaseDirectory + "Log\\Error");
                    }

                    Write($"{AppContext.BaseDirectory}Log\\Error\\Log_{DateTime.Today.ToString("yyyy-MM-dd")}.txt", "Error", state);
                    break;
            }
        }

        private static void Write<TState>(string path, string level, TState state)
        {
            using (var fileStream = new FileStream(path, FileMode.OpenOrCreate))
            {
                fileStream.Position = fileStream.Length;
                var message = Encoding.UTF8.GetBytes($"\r\n{DateTime.Now.ToString()} {level}:{state} \r\n");
                fileStream.Write(message, 0, message.Length);
            }
        }
    }
}
